package org.huang.zhen;

import java.awt.*;

public class BlockCanvas extends Canvas {
    final int BLOCK_PIXEL = 18;
    private static final int MAX_SIZE = 4 * 20;
    private Block mBlk;

    public BlockCanvas(int x, int y) {
        super();
        setSize(MAX_SIZE, MAX_SIZE);
        setBounds(x, y, MAX_SIZE, MAX_SIZE);
        mBlk = null;
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        drawBackground(g);
        drawLines(g);
    }
    private void drawBackground(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.LIGHT_GRAY);
        g2d.drawRect(0,0, MAX_SIZE, MAX_SIZE);
        g2d.fillRect(0,0, MAX_SIZE, MAX_SIZE);
    }

    private void drawLines(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.white);
        BasicStroke stroke = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 5.0f, new float[]{2,2}, 0);
        g2d.setStroke(stroke);
//        for (int i = 1; i < BLOCK_SIZE; i++) {
//            g2d.drawLine( BLOCK_PIXEL * i, 0 , BLOCK_PIXEL * i, BLOCK_PIXEL * GameMap.GAME_MAP_SIZE_ROW  );
//            g2d.drawLine(0, BLOCK_PIXEL * i, BLOCK_PIXEL * GameMap.GAME_MAP_SIZE_COL, BLOCK_PIXEL * i);
//        }
    }
    public void updateBlock(final Block blk) {
        mBlk = blk;
        repaint();
    }

    public void update(Graphics g) {
        // 方块要居中显示，需计算开始绘制的坐标
        drawBackground(g);
        int rows = mBlk.getHeight();
        int cols = mBlk.getWidth();
        int X = (MAX_SIZE - cols * BLOCK_PIXEL)/2;
        int Y = (MAX_SIZE - rows * BLOCK_PIXEL)/2;
        g.setColor(Color.PINK);
        for (int i = 0; i < rows; i ++) {
            for (int j = 0; j < cols; j++) {
                if (mBlk.getMap()[i][j] == 1) {
                    g.drawRect(X + j* BLOCK_PIXEL, Y + i * BLOCK_PIXEL, BLOCK_PIXEL, BLOCK_PIXEL);
                    g.fillRect(X + j* BLOCK_PIXEL, Y + i * BLOCK_PIXEL, BLOCK_PIXEL, BLOCK_PIXEL);
                }
            }
        }

        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.white);
        BasicStroke stroke = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 5.0f, new float[]{2,2}, 0);
        g2d.setStroke(stroke);
        for (int i = 0; i < rows; i ++) {
            for (int j = 0; j < cols; j++) {
                if (mBlk.getMap()[i][j] == 1) {
                    g2d.drawRect(X + j* BLOCK_PIXEL, Y + i * BLOCK_PIXEL, BLOCK_PIXEL, BLOCK_PIXEL);
                }
            }
        }
    }
}
